<template>
  <el-input v-model="code" class="w100%">
    <template v-if="!selfonly" #prepend>
      <ElButton @click="onClick">{{ parentCode ? parentCode + '.' : '选择上级' }}</ElButton>
    </template>
  </el-input>
</template>
<script setup lang="ts">
  import { ElButton, ElInput } from 'element-plus'
  import { h, ref } from 'vue';
  import { TreePanel } from '@/components/Panel';
  import { Column } from '@/seed-application/types';
  import { footer, popup } from '@/components/Popup';
  import { watch } from 'vue';

  const props = defineProps<{column: Column, modelValue?: string, selfonly?: boolean, multiple?: boolean}>()
  const column = props.column
  const emits = defineEmits(['update:modelValue'])

  const selfonly = props.selfonly
  const parentCode = ref();
  const code = ref()

  function onClick() {
    const popupProps = {title: `请选择${column.label}`, width: '30vw'}
    popup(popupProps, {
      default: () => h(TreePanel, {column, value: parentCode.value, multiple: props.multiple, props: {label: 'name'}, onChoose }),
      footer: footer(ok)
    })
  }

  let chooseCode: string
  const onChoose = (value) => {
    chooseCode = value
  }

  function ok() {
    parentCode.value = chooseCode
  }

  watch([() => code.value, () => parentCode.value], () => {
    const finalValue = (chooseCode ? chooseCode + '.' : '') + (code.value || '')
    emits('update:modelValue', selfonly ? (code.value || '') : finalValue)
  })

  watch(() => props.modelValue, (val) => {
    const pos = val ? val.lastIndexOf('.') : -1
    parentCode.value = pos > 0 ? props.modelValue.substring(0, pos) : ''
    code.value = props.modelValue ? props.modelValue.substring(pos + 1) : ''
  }, { immediate: true })
</script>